package com.game.base.app;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import androidx.multidex.MultiDexApplication;

import com.game.ad.xiaom.XiaoMiMgr;
import com.game.base.BuildConfig;
import com.game.base.R;
import com.game.base.auth.AuthUtils;
import com.game.base.dir.DirType;
import com.game.base.server.base.BmobManager;
import com.game.base.server.push.PushManager;
import com.game.base.utils.log.Logger;
import com.game.base.utils.psp.PSP;
import com.game.base.utils.toast.ToastUtil;
import com.game.base.x5.X5Manager;
import com.game.push.PushMgr;

/**
 * Created by Su on 2019/5/7.
 */
public class App extends MultiDexApplication {
    public static App sInstance;
    public static Long time;        // 服务器时间

    @Override
    public void onCreate() {
        sInstance = this;
        super.onCreate();
        initModule(getApplicationContext());
    }

    /**
     * 按等级初始化逻辑模块
     */
    public void initModule(final Context context) {
        if (isMainProcess()) {//主进程
            preInit(context);
        }
        DirType.init(context, context.getString(R.string.app_storage_name));
        PSP.getInstance().init(context);//初始化sharedPreferences存储，每个进程都初始化一次
        Logger.init(BuildConfig.DEBUG); //初始化日志打印，每个进程都初始化一次
    }

    /**
     * @return 是否为主进程
     */
    private boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return getApplicationInfo().packageName.equals(appProcess.processName);
            }
        }
        return false;
    }

    /**
     * 预加载，在进程初始化的时候加载一次
     */
    private static void preInit(Context context) {
        BmobManager.initBmob(context);      // 初始化数据SDK
        XiaoMiMgr.initXiaoM(sInstance);     // 小米广告
        X5Manager.initTBSX5(context);       // X5内核
        PushManager.startPush(context);     // 开启推送服务
        AuthUtils.initAuthSDK();            // 三方账号
        ToastUtil.init(context);            // 初始化toast提示

        PushMgr.initMIUIPush(context);  // 三方推送
    }

    /**
     * 获取版本号
     */
    public static String getVersionName() {
        try {
            PackageInfo pi = sInstance.getPackageManager().getPackageInfo(
                    sInstance.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

}
